package org.jeecg.modules.flink;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;

import java.util.Arrays;


public class Flink {
    public static void main(String[] args) throws Exception {
        //批处理
 /*       ExecutionEnvironment executionEnvironment = ExecutionEnvironment.getExecutionEnvironment();
        String filePath = "E:\\新建文件夹";
        DataSource<String> stringDataSource = executionEnvironment.readTextFile(filePath);
        stringDataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) {
                String[] split = s.split("\t");
                Arrays.stream(split).parallel().filter(s1 ->
                        StrUtil.isNotEmpty(s1)).forEach(s1 -> {
                    collector.collect(Tuple2.of(s1, 1));
                });
            }
        }).groupBy(0).sum(1).print();
     */
        //流处理
        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<Integer> integerDataStreamSource = executionEnvironment.addSource(new SourceFunction<Integer>() {
            @Override
            public void run(SourceContext<Integer> sourceContext) throws Exception {
               while (true) {
                   sourceContext.collect(RandomUtil.randomInt());
               }
            }

            @Override
            public void cancel() {

            }
        });
        integerDataStreamSource.print();
        executionEnvironment.execute();
    }

}
